package com.yonyou.portcity.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信工具类
 *
 * @author LuoYangyi
 * @create 2017 08 03 13:38
 */
public class WxUtil {
    private static final Logger log = LoggerFactory.getLogger(WxUtil.class);
	/*
	* requestUrl 请求的http接口路径
	* requestMethod 请求方式（GET/POST）
	* outputStr 请求时提交的数据
	*/
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
//            System.out.println("url=="+url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
//            System.out.println("httpUrlConn=="+httpUrlConn);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod)) {
                System.out.println("1111==" + requestMethod);
                try {
                    httpUrlConn.connect();
                }catch (Exception e){
                    System.out.println(e);
                    log.error("https request error111111:{}", e);
                }
            }
//            System.out.println("22222==" + requestMethod);
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        }
        return jsonObject;
    }
    /*
    * jsapi_ticket 调用微信JS接口的临时票据,必须有效。
    * para url 调用JS接口页面的完整URL。
	* ret 返回前端调用微信企业号JS_SDK扫一扫接口所需的参数
    */
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
//        System.out.println("nonce_str:"+nonce_str);
        String timestamp = create_timestamp();
//        System.out.println("timestamp:"+timestamp);
        String string1;
        String signature = "";
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str+ "&timestamp=" + timestamp + "&url=" + url;
//        System.out.println("string1:"+string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        System.out.println("signature:"+signature);
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }
	//byte转化为16进制
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    // 获取随机字符串nonce_str
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    // 获取时间戳timestamp
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
